<template>
  <div class="selectCityPopup">
    <u-popup :closeOnClickOverlay="true" :show="show" round="10px" mode="bottom" @close="getData" @open="open">
      <view class="popup">
        <div class="top">
          <div class="title">
            <span class="text">请选择城市</span>
            <span class="num" v-if="type == 'select'">已选 {{ (activeItem && activeItem.length) || 0 }} /{{ max }}</span>
            <span class="cur_ad" v-if="type == 'select' && getUserLocationInfo">
              <!-- <span class="iconfont cyweizhi"></span> -->
            </span>
            <!-- <span class="address" v-if="type == 'select'">{{ locationText }}</span> -->
          </div>
          <div class="location_text" v-if="type == 'getLocation'" @click="getLocation">
            <span class="iconfont cyweizhi">当前位置：</span>
            {{ locationText }}
          </div>
          <div class="location_text" v-else-if="type == 'select'" @click="getData">确认</div>
        </div>
        <div class="tags" v-if="activeItem && activeItem.length > 0 && type != 'getLocation'">
          <text class="tag_item" @click="deleteItem(index, item)" v-for="(item, index) in activeItem" :key="item.name">
            {{ item.name }}
            <text class="close">&times;</text>
          </text>
        </div>
        <div class="content">
          <scroll-view :scroll-top="scrollTop" scroll-y :style="{ height: '73vh', width: '91px' }">
            <div class="province_list">
              <div class="province_item" @click="selectProvince(index, item)" :class="[provinceActiveIndex == index && 'active']" v-for="(item, index) in provinceList" :key="index">
                {{ item.name }}
              </div>
            </div>
          </scroll-view>

          <div class="city_list">
            <span
              class="all item"
              v-if="sCurProvince && sCurProvince.id != 1"
              :class="[activeItem && activeItem.some(item1 => item1.id == sCurProvince.id) ? 'activeCity' : '']"
              @click="clickItem(sCurProvince.id, sCurProvince, 'all')"
            >
              全{{ sCurProvince.name }}
            </span>
            <div class="citylist">
              <div
                class="city_item"
                :class="[activeItem && activeItem.some(item1 => item1.id == item.id) ? 'activeCity' : '']"
                v-for="(item, index) in cityListData"
                :key="index"
                @click="clickItem(index, item, 'im')"
              >
                {{ item.fullname }}
              </div>
            </div>
          </div>
        </div>
      </view>
    </u-popup>
  </div>
</template>

<script>
import { mapMutations, mapGetters } from "vuex";
export default {
  name: "selectCityPopup",
  props: {
    show: {
      type: Boolean,
      default: false,
    },
    max: {
      type: Number,
      default: 1,
    },
    type: {
      type: String,
      default: "getLocation",
    },
    cityList2: {
      type: Array,
      default: () => {
        return [];
      },
    },
  },
  data() {
    return {
      // show: false,
      provinceActiveIndex: 0,
      provinceList: [],
      cityListData: [],
      countyListData: [],
      sCurProvince: null,
      activeItem: [],
      activeItemIndex: [],
      userLocationInfo: null,
      userSelectCity: null,
      postResumAddress: null,
      municipalityFilter: ["上海市", "北京市", "天津市", "重庆市"], //直辖市
      municipality: [],
      scrollTop: 0,
    };
  },
  computed: {
    ...mapGetters("location", ["getSelectCity", "getCurProvince", "getcurProvinceIndex", "getUserLocationInfo", "getMunicipality"]),
    locationText() {
      if (this.getSelectCity && this.getSelectCity.length) {
        return this.getSelectCity[0].fullname;
      }
      console.log("110this.getCurProvince", this.getCurProvince);
      if (this.getCurProvince) {
        return this.getCurProvince.text;
      }
      return "全国";
    },
  },
  onShow(options) {},
  methods: {
    ...mapMutations("location", ["setUserLocationInfo", "setcurProvinceIndex", "setSelectCity", "setcurProvince"]),
    open() {
      // this.show = true;
    },
    async init() {
      await this.getProvinceList();
      if (this.cityList2.length) {
        console.log("132", this.cityList2);
        if (this.municipalityFilter.includes(this.getSelectCity[0]["fullname"])) {
          // 是直辖市

          this.cityListData = this.municipality;
          // this.getMunicipality.forEach((item, index) => {
          //   if (item.id == this.getSelectCity[0]["id"]) {
          //     // this.$set(this, this.activeItem, item);
          //     this.activeItem = [item];
          //   } else {
          //   }
          // });
          this.activeItem = this.cityList2;
        } else {
          // 不是直辖市
          console.log("不是直辖市", this.sCurProvince);
          this.activeItem = this.cityList2;
          let idx = this.provinceList.findIndex(i => i.id == this.cityList2[0]["id"]);
          this.setcurProvince(this.sCurProvince);
          console.log("idx", idx);
          if (idx > -1) {
            //选中的是全省
            this.provinceActiveIndex = idx - 1;
            this.scrollTop = 40 * (this.provinceActiveIndex - 1);
            this.sCurProvince = this.provinceList[idx];
            this.setcurProvince(this.sCurProvince);
            await this.getCityList(this.provinceList[idx]["id"], "city");
          } else {
            if (this.getCurProvince) {
              let idx1 = this.provinceList.findIndex(i => i.id == this.getCurProvince["code"]);
              console.log("不是直辖市0", this.getCurProvince, idx1);
              if (idx1 > -1) {
                console.log("不是直辖市1", this.getCurProvince, idx1);
                this.provinceList.forEach((item, index) => {
                  if (item.id == this.cityList2[0].id.slice(0, 2) + "0000") {
                    this.setcurProvince(item);
                    this.sCurProvince = item;
                    this.provinceActiveIndex = index - 1;
                  }
                });
                // this.sCurProvince = this.provinceList[idx1];
                // this.setcurProvince(this.sCurProvince);

                this.scrollTop = 40 * (this.provinceActiveIndex - 1);
                await this.getCityList(this.getCurProvince["code"], "city");
              } else {
                console.log("不是直辖市2", this.getCurProvince, idx1);
                await this.getCityList(this.provinceList[0]["id"], "city");
              }
            } else {
              console.log("不是直辖市2", this.getCurProvince);
              await this.getCityList(this.provinceList[0]["id"], "city");
            }
          }
        }
      } else if (this.getSelectCity.length) {
        if (this.municipalityFilter.includes(this.getSelectCity[0]["fullname"])) {
          // 是直辖市
          console.log("是直辖市", this.getMunicipality, this.getSelectCity);
          this.cityListData = this.municipality;
          // this.getMunicipality.forEach((item, index) => {
          //   if (item.id == this.getSelectCity[0]["id"]) {
          //     // this.$set(this, this.activeItem, item);
          //     this.activeItem = [item];
          //   } else {
          //   }
          // });
          this.activeItem = JSON.parse(JSON.stringify(this.getSelectCity));
        } else {
          // 不是直辖市
          console.log("不是直辖市", this.sCurProvince);
          this.activeItem = JSON.parse(JSON.stringify(this.getSelectCity));
          let idx = this.provinceList.findIndex(i => i.id == this.getSelectCity[0]["id"]);
          this.setcurProvince(this.sCurProvince);
          console.log("idx", idx);
          if (idx > -1) {
            //选中的是全省
            this.provinceActiveIndex = idx - 1;
            this.scrollTop = 40 * (this.provinceActiveIndex - 1);
            this.sCurProvince = this.provinceList[idx];
            this.setcurProvince(this.sCurProvince);
            await this.getCityList(this.provinceList[idx]["id"], "city");
          } else {
            if (this.getCurProvince) {
              let idx1 = this.provinceList.findIndex(i => i.id == this.getCurProvince["code"]);
              console.log("不是直辖市0", this.getCurProvince, idx1);
              if (idx1 > -1) {
                console.log("不是直辖市1", this.getCurProvince, idx1);
                this.provinceList.forEach((item, index) => {
                  if (item.id == this.getSelectCity[0].id.slice(0, 2) + "0000") {
                    this.setcurProvince(item);
                    this.sCurProvince = item;
                    this.provinceActiveIndex = index - 1;
                  }
                });
                // this.sCurProvince = this.provinceList[idx1];
                // this.setcurProvince(this.sCurProvince);

                this.scrollTop = 40 * (this.provinceActiveIndex - 1);
                await this.getCityList(this.getCurProvince["code"], "city");
              } else {
                console.log("不是直辖市2", this.getCurProvince, idx1);
                await this.getCityList(this.provinceList[0]["id"], "city");
              }
            } else {
              console.log("不是直辖市2", this.getCurProvince);
              await this.getCityList(this.provinceList[0]["id"], "city");
            }
          }
        }
      } else if (this.userLocationInfo) {
        this.cityListData = this.getMunicipality;
        this.provinceList.forEach((item, index) => {
          if (item.fullname == this.userLocationInfo.ad_info.province) {
            this.sCurProvince = item;
            this.provinceActiveIndex = index - 1;
            this.scrollTop = 40 * (this.provinceActiveIndex - 1);
            this.activeItem.push(item);
            this.setSelectCity(item);
          }
        });
        console.log("this.activeItem", this.activeItem);
        if (this.municipalityFilter.includes(this.userLocationInfo.ad_info.city)) {
          this.cityListData = this.municipality;
          this.cityListData.forEach((item, index) => {
            if (item.fullname == this.userLocationInfo.ad_info.city) {
              this.activeItem.push(item);
              // this.$set(this, this.activeItem, item);
            }
          });
          console.log("this.activeItem1", this.cityListData, this.userLocationInfo.ad_info.city);
        } else {
          await this.getCityList(this.userLocationInfo.ad_info.adcode.slice(0, 2) + "0000", "city");
          console.log("this.sCurProvince", this.sCurProvince);
          this.cityListData.forEach((item, index) => {
            if (item.name == this.userLocationInfo.ad_info.city) {
              // this.activeItem.push(item);
              this.$set(this, this.activeItem, item);
            }
          });
        }
      } else {
        await this.getCityList(this.provinceList[this.provinceActiveIndex]["id"], "city");
      }
    },
    close() {
      this.$emit("close");
      // this.show = false;
    },
    getData() {
      this.setSelectCity(this.activeItem);
      this.$setStoraged("userSelectCity", this.activeItem);
      this.$emit("getData", this.activeItem);
      // this.show = false;
    },
    deleteItem(index, data) {
      this.activeItem.splice(index, 1);
      this.activeItemIndex.splice(index, 1);
    },
    clickItem(index, data, type) {
      console.log("111", JSON.parse(JSON.stringify(this.getSelectCity)));
      if (type == "all") {
        this.setcurProvince(data);
        this.activeItem = this.activeItem.filter(v => this.cityListData.every(val => val.id != v.id));
      }
      if (type == "im") {
        if (type == "all") {
          this.setSelectCity([data]);
          this.$setStoraged("userSelectCity", [data]);
          return this.activeItem.push(data);
        }
        this.provinceList.forEach((item, index) => {});
      }
      if (type == "im") {
        let idx = this.activeItem.findIndex(i => i.id == this.sCurProvince.id);
        if (idx >= 0) this.activeItem.splice(idx, 1);
      }
      this.activeItem.forEach((item1, index1) => {
        if (item1.fullname == data.fullname) {
          this.activeItem.slice(index1, 1);
          this.activeItemIndex.slice(index1, 1);
        }
      });
      if (this.activeItem && this.activeItem.length > 0) {
        if (this.activeItem.length == this.max) {
          return this.$layer.message("最多选择" + this.max + "个地址~");
        }
        let index = -1;
        for (let i = 0; i < this.activeItem.length; i++) {
          if (this.activeItem[i].fullname === data.fullname) {
            // 如果数组中已经存在当前点击对象，则记录下标
            index = i;
            break;
          }
        }
        // 如果当前点击对象已经在数组中存在，则删除该对象
        if (index !== -1) {
          this.activeItem.splice(index, 1);
        } else {
          // 如果当前点击对象在数组中不存在，则添加该对象
          if (this.activeItem && this.activeItem.length <= this.max - 1) {
            this.activeItem.push(data);
          }
        }
      } else {
        if (this.activeItemIndex.length <= this.max) {
          this.activeItem.push(data);
          this.activeItemIndex.push(index);
        }
      }
      if (this.activeItem.length == 1) {
        this.$setStoraged("SProvince", this.provinceList[this.provinceActiveIndex]);
      }
    },
    async getLocation() {
      if (this.$getStoraged("userLocationInfo")) {
        return false;
      }
      let res = await this.$getLocationPromise();
      if (res) {
        let res2 = await this.$http.request(
          "https://apis.map.qq.com/ws/geocoder/v1/?key=6KJBZ-ZB2W4-NXNUB-DT7KO-E4KMJ-7KB5L&location=" + res.latitude + "," + res.longitude,

          "GET",
          {},
          data => {
            this.$setStoraged("userLocationInfo", JSON.stringify(data.result));
            this.userLocationInfo = data.result;
            if (this.municipalityFilter.includes(data.result.ad_info.province)) {
              this.userLocationInfo.ad_info.district = data.result.ad_info.province;
            }
            let province = {
              fullname: this.userLocationInfo.ad_info.province,
              name: this.userLocationInfo.ad_info.province,
              id: this.userLocationInfo.ad_info.city_code.slice(3),
              location: this.userLocationInfo.location,
            };
            let city = {
              fullname: this.userLocationInfo.ad_info.district,
              name: this.userLocationInfo.ad_info.district,
              id: this.userLocationInfo.ad_info.adcode,
              location: this.userLocationInfo.location,
            };
            this.init();
            this.$emit("submit", {
              province: province,
              city: city,
            });
          }
        );
      }
    },
    async selectProvince(index, item) {
      this.provinceActiveIndex = index;
      this.scrollTop = 40 * this.provinceActiveIndex;
      this.sCurProvince = item;
      this.setcurProvince(item);

      this.$setStoraged("curProvinceIndex", index);
      console.log("310", item);
      this.setcurProvinceIndex(index);
      console.log(item);
      this.idx = null;
      await this.getCityList(item.id, "city");
    },
    async getProvinceList() {
      let reslut = await this.$getMap.getProvinceList();
      try {
        reslut.forEach((item, index) => {
          if (this.municipalityFilter.includes(item.fullname)) {
            this.municipality.push(item);
            // reslut.splice(index, 1);
            console.log(this.municipality);
          }
        });

        reslut.unshift({
          fullname: "直辖市",
          name: "直辖市",
          id: 1,
        });

        this.provinceList = JSON.parse(JSON.stringify(reslut));

        this.sCurProvince = reslut[this.provinceActiveIndex];

        this.provinceList.forEach((item, index) => {
          if (this.municipalityFilter.includes(item.fullname)) {
            this.provinceList.splice(index, 1);
          }
        });
        setTimeout(() => {
          this.provinceList.forEach((item, index) => {
            if (this.municipalityFilter.includes(item.fullname)) {
              this.provinceList.splice(index, 1);
            }
          });
        }, 0);
      } catch (error) {}
    },
    async getCityList(id, type) {
      if (id == 1) {
        this.cityListData = this.municipality;
        return false;
      }
      let list = await this.$getMap.getCityList(id);
      if (type == "city") {
        this.cityListData = list;
      } else {
        this.countyListData = list;
      }
    },
  },
  watch: {},
  async created() {
    this.$throttle(this.init);
  },
  // 组件周期函数--监听组件挂载完毕
  mounted() {},
  // 组件周期函数--监听组件数据更新之前
  beforeUpdate() {},
  // 组件周期函数--监听组件数据更新之后
  updated() {},
  // 组件周期函数--监听组件激活(显示)
  activated() {},
  // 组件周期函数--监听组件停用(隐藏)
  deactivated() {},
  // 组件周期函数--监听组件销毁之前
  beforeDestroy() {},
};
</script>

<style scoped lang="scss">
.selectCityPopup {
  .popup {
    height: 80vh;
    .top {
      width: 90%;
      height: 53px;
      line-height: 53px;
      display: flex;
      justify-content: space-between;
      margin: 0 auto;
      background: #fff;
      font-size: 16px;
      .title {
        font-family: PingFang SC-Semibold, PingFang SC;
        font-weight: 600;
        color: #333333;
        .num {
          font-size: 14px;
          font-family: PingFang SC-Regular, PingFang SC;
          font-weight: 400;
          color: #999999;
          margin-left: 10px;
        }
        .cur_ad {
          font-size: 14px;
          font-family: PingFang SC-Regular, PingFang SC;
          font-weight: 400;
          color: #333333;
          .iconfont {
            font-size: 14px;
            color: #ff8822;
            margin: 0 2px 0 11px;
          }
        }
        .address {
          margin-left: 6px;
          font-size: 14px;
          font-family: PingFang SC-Regular, PingFang SC;
          font-weight: 400;
          color: #ff8822;
        }
        .location_text {
          margin-left: 10px;
        }
      }
      .location_text {
        font-size: 14px;
        font-family: PingFang SC-Regular, PingFang SC;
        font-weight: 400;
        color: #ff8822;
        .iconfont {
          color: #333333;
        }
      }
    }
    .tags {
      height: 36px;
      width: 100%;
      box-sizing: border-box;
      padding: 0 16px;
      margin-bottom: 9px;
      .tag_item {
        // max-width: 70px;
        height: 100%;
        background: #ffedde;
        border-radius: 4px 4px 4px 4px;
        font-size: 14px;
        font-family: PingFang SC-Regular, PingFang SC;
        font-weight: 400;
        color: #ff8822;
        padding: 6px 17px;
        box-sizing: border-box;
        position: relative;
        margin-right: 20px;
        .close {
          position: absolute;
          width: 16px;
          height: 16px;
          font-size: 16px;
          background: #ff8822;
          color: #fff;
          top: -4px;
          right: -8px;
          border-radius: 50%;
          line-height: 14px;
          text-indent: 3px;
        }
      }
    }
    .content {
      width: 100%;
      display: flex;
      .province_list {
        width: 91px;
        line-height: 40px;
        // height: 900px;
        overflow-y: scroll;
        background: #f7f7f7;
        text-align: center;
      }
      .province_item {
        font-size: 14px;
        font-family: PingFang SC-Semibold, PingFang SC;
        font-weight: 600;
        color: #333333;
      }
      .active {
        position: relative;
        background: #fff;
        &::after {
          position: absolute;
          content: "";
          width: 4px;
          height: 13px;
          background: #ff8822;
          border-radius: 0px 0px 0px 0px;
          opacity: 1;
          left: 0;
          top: 50%;
          transform: translateY(-50%);
        }
      }
      .city_list {
        width: 284px;
        background: #ffffff;
        border-radius: 0px 0px 0px 0px;
        opacity: 1;
        // overflow: hidden;
        overflow-y: scroll;
        padding: 6px 15px;
        border: 1px solid transparent;
        .item {
          background: #ffffff;
          border-radius: 4px 4px 4px 4px;
          border: 1px solid #e2e2e2;
          padding: 6px 18px;
          // box-sizing: border-box;
          font-size: 14px;
          font-family: PingFang SC-Regular, PingFang SC;
          font-weight: 400;
          color: #666666;
          margin: 70px 20px 20px 0px;
        }
        .citylist {
          display: flex;
          flex-wrap: wrap;
          margin-top: 20px;
          .city_item {
            width: 75px;
            height: 32px;
            text-align: center;
            line-height: 32px;
            // min-width: 33%;
            background: #ffffff;
            border-radius: 4px 4px 4px 4px;
            border: 1px solid #e2e2e2;
            // padding: 6px 15px;
            margin: 6px 10px 6px 0px;
            font-size: 14px;
            font-family: PingFang SC-Regular, PingFang SC;
            font-weight: 400;
            color: #666666;
            @include ells(1);
          }
          .city_item:nth-child(3n) {
            margin-right: 0px !important;
          }
          @media screen and (min-width: 250px) {
            .city_item:nth-child(3n) {
              margin-right: 10px;
            }
          }
        }
        .all {
        }
      }
    }
  }

  .activeCity {
    background-color: #ff8822 !important;
    color: #fff !important;
  }
  .disable {
    background: #999999 !important;
    color: #fff !important;
  }
}
</style>
